//
//  CCYMeViewController.m
//  模拟-百思不得姐
//
//  Created by 程春玉 on 16/8/1.
//  Copyright © 2016年 chunyu. All rights reserved.
//

#import "CCYMeViewController.h"
#import "CCYMeRegistTableViewCell.h"
#import "CCYMeSubListTableViewCell.h"
#import "AFNetworking.h"
#import "SVProgressHUD.h"
#import "CCYMeActivityModel.h"
#import "CCYMeModel.h"
#import "LoginViewController.h"
#import "CCYSubscribeTableViewController.h"
#import "CCYToolTableViewController.h"
#import "JXPMapViewController.h"

@interface CCYMeViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tab;
// 活动模型数组
@property (nonatomic, strong) NSMutableArray *activityArr;
// 关注模型数组
@property (nonatomic, strong) NSMutableArray *recommendArr;
// 确保两个模型数据都解析完毕后，刷新tableView
@property (nonatomic, strong) NSMutableArray *allData;

@end

@implementation CCYMeViewController

// 活动模型数组懒加载
- (NSMutableArray *)activityArr
{
    if (!_activityArr) {
        _activityArr = [[NSMutableArray alloc] init];
    }
    return _activityArr;
}
// 关注模型数组懒加载
- (NSMutableArray *)recommendArr
{
    if (!_recommendArr) {
        _recommendArr = [[NSMutableArray alloc] init];
    }
    return _recommendArr;
}

- (NSMutableArray *)allData
{
    if (!_allData) {
        _allData = [[NSMutableArray alloc] init];
    }
    return _allData;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpView];
    [self createTab];
    [self analyActivityData];
    [self analyRecommendData];
    [self setmapBtn];
    
    // 注册登录通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Action:) name:@"login" object:nil];
    // 注册注销通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Action:) name:@"loginOut" object:nil];
}

- (void)Action:(NSNotification *)ation
{

    XMGLog(@"1111");
   
    
    
    

    CCYMeRegistTableViewCell *cell = [_tab cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    if ([ation.name isEqualToString:@"login"]) {
        cell.logBtn.text = [[EMClient sharedClient] currentUsername];
    } else {
        cell.logBtn.text = @"登录/注册";
    }
}

- (void)setmapBtn{
    UIBarButtonItem *mapBtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"mapImage"] style:UIBarButtonItemStylePlain target:self action:@selector(mapIn)];
    self.navigationItem.leftBarButtonItem = mapBtn;
}
- (void)mapIn{
    UIViewController *vc = [[JXPMapViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)viewDidAppear:(BOOL)animated
{
    CCYMeRegistTableViewCell *cell = [_tab cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    if ([[EMClient sharedClient] currentUsername] != nil && [cell.logBtn.text isEqualToString:@"登录/注册"]) {
        cell.logBtn.text = [[EMClient sharedClient] currentUsername];
    }

}

// 设置页面初始化设置
- (void)setUpView
{
    self.navigationItem.title = @"我的";
    UIBarButtonItem *tool = [UIBarButtonItem itemWithImage:@"mine-setting-icon" selectImage:@"mine-setting-icon-click" target:self action:@selector(MeClick)];
    self.navigationItem.rightBarButtonItem = tool;
    self.view.backgroundColor = XMGVColor;
}
// 设置按钮点击方法
- (void)MeClick
{
    [self.navigationController pushViewController:[[CCYToolTableViewController alloc] init] animated:YES];
}

// 创建tableView
- (void)createTab
{
    self.tab = [[UITableView alloc] initWithFrame:self.view.bounds style:(UITableViewStylePlain)];
    _tab.backgroundColor = [UIColor clearColor];
    _tab.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tab registerNib:[UINib nibWithNibName:@"CCYMeRegistTableViewCell" bundle:nil] forCellReuseIdentifier:@"CCYMeRegistTableViewCell"];
    [_tab registerNib:[UINib nibWithNibName:@"CCYMeCollorViewTableViewCell" bundle:nil] forCellReuseIdentifier:@"CCYMeCollorViewTableViewCell"];
    [_tab registerNib:[UINib nibWithNibName:@"CCYMeSubListTableViewCell" bundle:nil] forCellReuseIdentifier:@"CCYMeSubListTableViewCell"];
    _tab.delegate = self;
    _tab.dataSource = self;
    [self.view addSubview:_tab];
}

// 解析活动数据
- (void)analyActivityData
{
    NSDictionary *dic = @{@"a" : @"square", @"c" : @"topic"};
    NSString *url = @"http://api.budejie.com/api/api_open.php";
    [[AFHTTPSessionManager manager] GET:url parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        for (NSDictionary *temp in responseObject[@"square_list"]) {
            CCYMeActivityModel *model = [[CCYMeActivityModel alloc] init];
            [model setValuesForKeysWithDictionary:temp];
            [self.activityArr addObject:model];
        }
        [self.allData addObject:@"活动数据解析完毕"];
        // 只有当两个模型数组都接续完毕，才回到主线程刷新tableview
        if (self.allData.count == 2) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tab reloadData];
            });
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"活动加载失败，请检查网络"];
    }];
}

// 解析推荐标签数据
- (void)analyRecommendData
{
    NSDictionary *dic = @{@"a" : @"tag_recommend", @"action" : @"sub", @"c" : @"topic"};
    NSString *url = @"http://api.budejie.com/api/api_open.php";
    [[AFHTTPSessionManager manager] GET:url parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        for (NSDictionary *temp in responseObject) {
            CCYMeModel *model = [[CCYMeModel alloc] init];
            [model setValuesForKeysWithDictionary:temp];
            [self.recommendArr addObject:model];
        }
        [self.allData addObject:@"标签数据解析完毕"];
        // 只有当两个模型数组都接续完毕，才回到主线程刷新tableview
        if (self.allData.count == 2) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tab reloadData];
            });
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"标签加载失败，请检查网络"];
    }];
}

// 返回分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
// 返回分区高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section != 1) {
        return 13;
    }
    return 40;
}
// 分区视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section != 1) {
        UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 13)];
        v.backgroundColor = XMGVColor;
        return v;
    }
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 53)];
    headView.backgroundColor = [UIColor whiteColor];
    UIView *headBlackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 13)];
    headBlackView.backgroundColor = XMGVColor;
    [headView addSubview:headBlackView];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(25, 19, 100, 20)];
    label.text = @"推荐订阅";
    label.font = [UIFont systemFontOfSize:14];
    [headView addSubview:label];
    return headView;
    
}

// cell的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1) {
        return self.recommendArr.count;
    }
    return 1;
}
// cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 60;
    }
    return 70;
}

// cell的样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        CCYMeRegistTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CCYMeRegistTableViewCell" forIndexPath:indexPath];
        return cell;
    }
    CCYMeSubListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CCYMeSubListTableViewCell" forIndexPath:indexPath];
    [cell setMessageWithModel:self.recommendArr[indexPath.row]];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if ([[EMClient sharedClient] currentUsername] == nil) {
            [self presentViewController:[[LoginViewController alloc] init] animated:YES completion:nil];
        }
    } else {
        CCYSubscribeTableViewController *sub = [[CCYSubscribeTableViewController alloc] initWithStyle:(UITableViewStylePlain)];
        sub.theme_id = [self.recommendArr[indexPath.row] theme_id];
        [self.navigationController pushViewController:sub animated:YES];
    }
}



@end
